package fi.foyt.cs.actions.friends;

import org.restlet.data.Form;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;

import fi.foyt.cs.actions.ActionResource;
import fi.foyt.cs.api.events.FriendEventsDispatcher;
import fi.foyt.cs.controller.SystemController;
import fi.foyt.cs.controller.UserController;
import fi.foyt.cs.persistence.domainmodel.system.ExternalLinkVerificationCode;
import fi.foyt.cs.persistence.domainmodel.user.User;
import fi.foyt.cs.persistence.domainmodel.user.UserFriend;

public class AcceptResource extends ActionResource {
  
  @Get
  public Representation represent() throws ResourceException {  
    Form query = getQuery();

    SystemController systemController = new SystemController();
    UserController userController = new UserController();

    String verificationCode = query.getFirstValue("elvc");
    ExternalLinkVerificationCode externalLinkVerificationCode = systemController.findExternalLinkVerificationCodeByVerificationCode(verificationCode);
    Long friendId = getExtraParameterLong(externalLinkVerificationCode, "friendId");
    
    User user = userController.findUserById(externalLinkVerificationCode.getUserId());
    User friend = userController.findUserById(friendId);
    UserFriend userFriend = userController.findUserFriendByUserAndFriend(friend, user);
    userController.updateUserFriendConfirmed(userFriend, Boolean.TRUE);
    
    FriendEventsDispatcher.getInstance().sendFriendshipAcceptedEvent(user, friend);
    
    return new StringRepresentation("Friendship accepted successfully.");
  }
}
